package com.xncoding.freemarker.filter;


import org.apache.commons.lang.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.apache.commons.lang.StringEscapeUtils;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
//@Order(2)
//@Component
//@WebFilter(filterName = "apiAccessFilter", urlPatterns = "/*")
public class ApiAccessFilter implements Filter {
    private  byte[] body;
    String[] strArr = {"\"","%","'"};

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException{

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String method  = (httpServletRequest.getMethod());
        Map<String, String[]> map = httpServletRequest.getParameterMap();
        ServletRequest requestWrapper = null;
        GetParameterRequestWrapper requestWrapper1= null;
        if(httpServletRequest.getMethod().equals("POST")){
            requestWrapper = new PostParameterRequestWrapper(httpServletRequest,method,map);
            chain.doFilter(requestWrapper, response);
        }else if(httpServletRequest.getMethod().equals("GET")){
            requestWrapper1 = new GetParameterRequestWrapper((HttpServletRequest)request);
            Set<String> key = map.keySet();
            for(String arr :strArr){
                for(String k : key){
                    String[] arrValues =  map.get(k);
                    String newValues= StringUtils.join(arrValues);
                    if(newValues.contains(arr)){
                        //对不合法参数转义
                        String escape = StringEscapeUtils.escapeXml(arr);
                        String s1 = newValues.replace(arr,escape);
                        //重新put相同的key，替换对应的values
                        requestWrapper1.addParameter(k, new String[]{s1});
                    }
                }
            }
            chain.doFilter(requestWrapper1, response);
        }
    }

    @Override
    public void destroy() {

    }


}
